﻿using System.Web.Mvc;
using Myotragus.Data.RepositoryExtensions;
using Myotragus.Store.Model.DefaultRepositories;
using Myotragus.Store.Model.Helpers;
using Myotragus.Store.Models;

namespace Myotragus.Store.Controllers
{
  public class ProductController : Controller
  {
    private IProductRepository _repository;
    public IProductRepository Repository
    {
      get
      {
        return _repository ?? (_repository = Core.Container.Resolve<IProductRepository>());
      }
    }

    public ActionResult Index()
    {
      return View(Repository.FindAll(CultureHelper.Current.LCID));
    }

    public ActionResult Details(int id)
    {
      return View(Repository.Load(CultureHelper.Current.LCID, id));
    }

    public ActionResult Edit(int id, string culture)
    {
			if (id == 0)
				return View(Repository.New());
      
			culture = culture ?? CultureHelper.Current.Name;
      var lcId = CultureHelper.GetCulture(culture).LCID;

      return View(Repository.Load(lcId, id));
    }

    [HttpPost]
    public ActionResult Edit(int id, string culture, FormCollection postData)
    {
      culture = culture ?? CultureHelper.Current.Name;
      var lcId = CultureHelper.GetCulture(culture).LCID;

      var item = Repository.Load(lcId, id);
      UpdateModel(item, postData);
      Repository.Save(lcId, item);
      ViewData["culture"] = culture;

      return RedirectToAction("Edit", new { id, locale = culture });
    }

    public ActionResult Delete(int id)
    {
      var item = Repository.Load(CultureHelper.Current.LCID, id);
      Repository.Delete(item);

      return RedirectToAction("Index");
    }
  }
}
